import {server} from '../api/config'
import axios from 'axios'
import router from '../router'
import store from '../util/store'
import {Message, Loading} from 'element-ui';
import qs from 'qs'

// axios 配置
axios.defaults.timeout = 1000000

// 添加请求拦截器
let loadingWin;
axios.interceptors.request.use(function (config) {
  loadingWin = Loading.service({
    text: '加载中'
  });
  return config
}, function (error) {
  return Promise.reject(error)
})

// 添加响应拦截器
axios.interceptors.response.use(function (response) {
  loadingWin.close();
  return response
}, function (error) {
  return Promise.reject(error)
})

function handleUrl(url) {
  if (store.get('token')) {
    return server + url
  } else {
    return server + url
  }
}

/**
 * 处理请求异常
 * @param err
 */
function handleError(reject, err) {
  if (err.message.indexOf('Network Error') >= 0) {
    Message.error('网络异常')
  } else if (err.message.indexOf('timeout') >= 0) {
    Message.error('请求超时,请刷新重试')
  }
  reject(err)
}

/**
 * 处理请求成功
 * @param response
 */
function handleSuccess(resolve, response) {
  if (response.data.code == 2010) { // 登录失效
    Message.error(response.data.msg)
    router.push('/login')
  } else if (response.data.code != 200) {
    Message.error(response.data.msg)
  } else {
    resolve(response.data)
  }
}

const http = {
  // 错误全局提示
  get(url, params, headers = {'token': store.get('token')}) {
    return new Promise((resolve, reject) => {
      axios({
        method: 'get',
        url: handleUrl(url),
        params: params,
        headers: headers
      }).then(response => {
          handleSuccess(resolve, response)
        },
        err => {
          handleError(reject, err)
        })
    })
  },
  post(url, params, headers = {'token': store.get('token')}) {
    return new Promise((resolve, reject) => {
      axios({
        method: 'post',
        url: handleUrl(url),
        data: qs.stringify(params),
        headers: headers
      }).then(response => {
          handleSuccess(resolve, response)
        },
        err => {
          handleError(reject, err)
        })
    })
  },
  axios: axios
}

export default http
